package compnents

import (
	"centerServer/models"
	"centerServer/utils"
	"crypto/md5"
	"encoding/hex"
	"encoding/xml"
	"fmt"
	"github.com/astaxie/beego/logs"
	"io/ioutil"
	"math/rand"
	"strconv"
	"strings"
	"sync"
	"time"
)

//type BonusLingQian struct {
//	XMLName      xml.Name `xml:"xml"`
//	Appid        string   `xml:"mch_appid"`
//	Mch_id       string   `xml:"mchid"`
//	Nonce_str    string   `xml:"nonce_str"`
//	Mch_billno   string   `xml:"partner_trade_no"`
//	Openid    	 string   `xml:"openid"`
//	CheckName	 string	  `xml:"check_name"`
//	Amount		 string	  `xml:"amount"`
//	Desc         string	  `xml:"desc"`
//	Sign         string   `xml:"sign"`
//}

const ()

var wxLingQianIns *WxLingQianCompnent
var onceA sync.Once

func GetWxLingQianCompnent() *WxLingQianCompnent {
	onceA.Do(func() {
		wxLingQianIns = &WxLingQianCompnent{}
		wxLingQianIns.InitCompnet()
	})
	return wxLingQianIns
}

type WxLingQianCompnent struct {
}

func (this *WxLingQianCompnent) InitCompnet() {

}

//  发送红包奖励 openid(用户ID) price(金额)
func (this *WxLingQianCompnent) SendBonus(oid string, price int, machappid string, sData *models.BonusLingQianDataModel) (isSuccess bool, err error) {
	openid := oid         //openid
	total_amount := price //金额

	//生成随机数并md5加密随机数
	rand.Seed(time.Now().UnixNano())
	md5Ctx1 := md5.New()
	md5Ctx1.Write([]byte(strconv.Itoa(rand.Intn(1000))))
	nonce_str := hex.EncodeToString(md5Ctx1.Sum(nil)) //随机数
	//订单号
	mch_billno := MCH_ID + time.Now().Format("20060102") + strconv.FormatInt(time.Now().Unix(), 10)
	// 参数map
	var argsKeyMap map[string]interface{}
	argsKeyMap = make(map[string]interface{})
	argsKeyMap["mch_appid"] = machappid
	argsKeyMap["mchid"] = MCH_ID
	argsKeyMap["nonce_str"] = nonce_str
	argsKeyMap["partner_trade_no"] = mch_billno
	argsKeyMap["openid"] = openid
	argsKeyMap["check_name"] = "NO_CHECK"
	argsKeyMap["amount"] = strconv.Itoa(total_amount)
	argsKeyMap["desc"] = DESC
	s1 := utils.FormatSign(argsKeyMap)
	s1 += "&key=" + KEY
	logs.Debug(s1)
	//argsKeyMap["key"] = KEY
	md5Ctx2 := md5.New()
	md5Ctx2.Write([]byte(s1))
	s1 = hex.EncodeToString(md5Ctx2.Sum(nil))
	sign := strings.ToUpper(s1) //签名

	v := &models.BonusLingQian{
		Appid:      models.CDATA{Text: MACH_APPID},
		Mch_id:     models.CDATA{Text: MCH_ID},
		Nonce_str:  models.CDATA{Text: nonce_str},
		Mch_billno: models.CDATA{Text: mch_billno},
		Openid:     models.CDATA{Text: openid},
		CheckName:  models.CDATA{Text: "NO_CHECK"},
		Amount:     models.CDATA{Text: strconv.Itoa(total_amount)},
		Desc:       models.CDATA{Text: DESC},
		Sign:       models.CDATA{Text: sign},
	}
	sData.FillLinqQianRequestData(v)
	output, err := xml.MarshalIndent(v, "  ", "    ")
	if err != nil {
		fmt.Printf("error: %v\n", err)
	}
	str2 := string(output[:])
	logs.Debug(str2)
	//POST数据
	httpReques, errA := SecurePost(LINQIAN_URL, output)
	if errA != nil {
		return false, errA
	}

	defer httpReques.Body.Close()
	bodyByte, _ := ioutil.ReadAll(httpReques.Body)
	var res models.WithdrawResult
	xmlerr := xml.Unmarshal(bodyByte, &res)
	if xmlerr != nil {
		//return xmlerr.Error(), "", false
		return false, xmlerr
	}
	if res.ReturnCode == "SUCCESS" && res.ResultCode == "SUCCESS" {
		return true, nil
	}
	return false, nil
}
